﻿using NightskyMimic.Core;
using System;
using System.Collections.Generic;
using System.Linq;

namespace NightskyMimic.Util
{
    public static class Grapviz
    {
        public static string Graph(List<State> leaves) 
        {
            int cont = 0;
            String result = String.Empty;
            List<string> lines = new List<string>();
            List<State> toDraw = new List<State>(leaves);

            while (toDraw.Count > 0) 
            {
                State node = toDraw[0];
                toDraw.RemoveAt(0);

                if (node.Parent != null) 
                {
                    lines.Add("n" + node.Parent.Id + " -> " + "n" + node.Id + '\n');
                    lines.Add("n" + node.Id + " [label=\"" + node.ToString() + "\"]\n");
                    cont++;
                    if (!toDraw.Any(x => x.Id == node.Parent.Id))
                        toDraw.Add(node.Parent);
                }
            }
            lines.Reverse();
            foreach (String l in lines) 
                result += l;

            return "digraph g{" + result + "}";
        }


        internal static string Graph(State root)
        {
            List<string> lines = new List<string>();
            List<State> toDraw = new List<State>() { root };
            String result = String.Empty;

            while (toDraw.Count > 0) 
            {
                State node = toDraw[0];
                toDraw.RemoveAt(0);
                if (node.Parent != null)
                {
                    result += "n" + node.Parent.Id + " -> " + "n" + node.Id + '\n';
                    result += "n" + node.Id + " [label=\"" + node.ToString() + "\"]\n";
                }
                toDraw.AddRange(node.Children);
            }

            return "digraph g{" + result + "}";
        }
    }
}
